package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.model.BannerModel;
import com.pengcheng.taskapplication.model.CommitOrderModel;
import com.pengcheng.taskapplication.model.ParkOrderModel;
import com.pengcheng.taskapplication.model.SubscribeOrderModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenter;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.net.ConvertUtil;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

/**
 * Created by ZFT on 2020/10/28.
 */

public class ParkScanActivity extends BaseActivity implements IView {

    @BindView(R.id.tv_center_title)
    TextView tv_center_title;

    @BindView(R.id.img_show)
    ImageView img_show;
//
//    @BindView(R.id.top_banner)
//    MZBannerView topZannerView;

    private UserPresenterV2 userPresenter;

    private String uid;
    private String newtoken;

    private static final int REQUEST_CODE = 121;

    @Override
    protected int layoutResID() {
        return R.layout.activity_park_layout;
    }

    @Override
    protected void initData() {
        tv_center_title.setText("智慧停车");
        img_show.setVisibility(View.GONE);
        userPresenter = new UserPresenterV2(this);

        //模拟进厂
        uid = SPUtils.getString(context, ConstantValue.SpType.userid);
        newtoken = SPUtils.getString(context, ConstantValue.SpType.newtoken);
        //getBanner();
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if (actionType.equals(ConstantValue.RequestKey.commitOrder)) {

            Gson gson = new Gson();
            Type type = new TypeToken<ParkOrderModel>() {
            }.getType();
            ParkOrderModel parkOrderModel = gson.fromJson(gson.toJson(data), type);

            Intent intent = new Intent(context, ConfrimOrderActivity.class);
            intent.putExtra("tradno", parkOrderModel.getTradno());
            startActivity(intent);
            ParkScanActivity.this.finish();

        }
        if (actionType.equals(ConstantValue.RequestKey.cancelapply)) {
            ToastUtils.showShortToast(msg);
            ParkScanActivity.this.finish();
        }
        if (actionType.equals(ConstantValue.RequestKey.getBanner)) {
            ArrayList<BannerModel> bannerModels = (ArrayList<BannerModel>) data;
            //setTopBanner(bannerModels);
        }


    }

    @Override
    public void onFailed(String code, String msg) {

    }

//    private void setTopBanner(List<BannerModel> banners){
//        topZannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                //Log.e("zw","onPageScrolled---->"+position);
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//        topZannerView.setPages(banners, new MZHolderCreator<TopBannerViewHolder>() {
//            @Override
//            public TopBannerViewHolder createViewHolder() {
//                return new TopBannerViewHolder();
//            }
//        });
//
//        topZannerView.start();
//        topZannerView.setIndicatorVisible(true);
//
//    }

    @OnClick({R.id.img_back, R.id.img_show, R.id.ll_scan})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_show:
                //进入订单列表页面
                intent = new Intent(context, MyParkList.class);
                startActivity(intent);
                finish();
                break;
            case R.id.ll_scan:
                //进入扫码页面,判断权限
                AndPermission.with(this)
                        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Intent intent = new Intent(context, QrScanActivity.class);
                                startActivityForResult(intent, REQUEST_CODE);
                            }
                        })
                        .onDenied(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                Toast.makeText(context, "没有权限", Toast.LENGTH_LONG).show();
                            }
                        }).start();
                break;
        }
    }


    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    //模拟出厂
//                    CommitOrderModel commitOrderModel=new CommitOrderModel();
//                    commitOrderModel.setUid(uid);
//                    commitOrderModel.setToken(newtoken);
//                    commitOrderModel.setParkid("5246181862404622040");
//                    commitOrderModel.setLaneno("5397052605423973596");

                    if (ConvertUtil.validate(result)) {
                        try {
                            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result).getAsJsonObject();
                            String type = jsonObject.get("type").getAsString();
                            if (type.equals("parkIn")) {
                                //获取停车场的id 和通道
                                String parkid = jsonObject.get("parkid").getAsString();
                                String laneno = jsonObject.get("laneno").getAsString();
                                //进入通道
                                inPark(newtoken, uid, parkid, laneno);
                            } else if (type.equals("parkExit")) {
                                //获取停车场的id 和通道
                                String parkid = jsonObject.get("parkid").getAsString();
                                String laneno = jsonObject.get("laneno").getAsString();
                                //进入通道
                                outPark(newtoken, uid, parkid, laneno);
                            }
                        } catch (Exception e) {
                            ToastUtils.showShortToast("请扫码正确的二维码");
                        }
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(context, "解析二维码失败,请重新扫码", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    public void inPark(String token, String uid, String parkid, String laneno) {
        userPresenter.commitOrder(token, uid, parkid, laneno, ConstantValue.RequestKey.inPark);
    }

    public void outPark(String token, String uid, String parkid, String laneno) {
        userPresenter.commitOrder(token, uid, parkid, laneno, ConstantValue.RequestKey.commitOrder);
    }

    public void getBanner() {
        userPresenter.getBanner(ConstantValue.RequestKey.getBanner);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //     topZannerView.pause();
    }
}
